package com.guc.coroutines.vm

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.guc.coroutines.db.FileCache
import com.guc.coroutines.db.ImageCacheUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * Created by guc on 2021/10/14.
 * Description：数据库缓存ViewModel
 */
class DatabaseViewModel:ViewModel() {
    private val _fileCache = MutableLiveData<List<FileCache>>()
    val fileCache = _fileCache

    fun getAll(){
        viewModelScope.launch (Dispatchers.IO){
            val fileCaches = ImageCacheUtil.getCacheDao().getAll()
            _fileCache.postValue(fileCaches)
        }
    }

    fun queryById( id:String){
        viewModelScope.launch (Dispatchers.IO){
            val file = ImageCacheUtil.getCacheDao().getCacheByFileId(id)
            file?.apply {
                _fileCache.postValue(listOf(this))
            }?:apply {
                _fileCache.postValue(listOf())
            }

        }
    }
}